package com.bnyy.medicalHousekeeper.base;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.ScreenUtils;
import com.bnyy.gbp.ScreenHelper;
import com.bnyy.gbp.StatusBarUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;

public abstract class BaseActivity extends AppCompatActivity {

    public LayoutInflater inflater;
    public AppCompatActivity mContext;
    public EventBus mEventBus;
    public SmartRefreshLayout mRefreshLayout;
    public LinearLayout optionsContainer, rootContainer;

    TextView title;
    View titleBar, back;

    private static AppCompatActivity activity;

    public abstract AppCompatActivity getSelfActivity();

    public abstract int getLayoutId();

    public abstract String getTitleStr();

    public abstract boolean registerEventBus();

    public abstract OnRefreshListener registerOnRefreshListener();

    public abstract OnLoadMoreListener registerOnLoadMoreListener();

    public abstract LocationPermissionIsGrantListener registerLocationPermissionIsGrantListener();

    private BaseActivityImpl.LocationPermissionIsGrantListener l;

    /**
     * 不使用下拉上拉控件
     *
     * @return
     */
    public abstract boolean unuseRefreshLayout();

    public static <T extends BaseActivity> void show(Context context, Class<T> clazz) {
        context.startActivity(new Intent(context, clazz));
    }

    public static <T extends BaseActivity> void show(Context context) {
        context.startActivity(new Intent(context, activity.getClass()));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        mEventBus = EventBus.getDefault();
        if (registerEventBus()) {
            mEventBus.register(this);
        }

        setContentView(com.bnyy.gbp.R.layout.layout_base);
//        tag = App.addActivity(getSelfActivity());
        activity = getSelfActivity();
        mContext = getSelfActivity();
        rootContainer = findViewById(com.bnyy.gbp.R.id.container);
        titleBar = findViewById(com.bnyy.gbp.R.id.title_bar);
        optionsContainer = findViewById(com.bnyy.gbp.R.id.options_container);
        back = findViewById(com.bnyy.gbp.R.id.back);
        back.setOnClickListener(view -> onBackPressed());
        if (TextUtils.isEmpty(getTitleStr())) { // 暂定以有无标题为条件判断是否显示标题栏
            titleBar.setVisibility(View.GONE);
        } else {
            title = findViewById(com.bnyy.gbp.R.id.tv_title);
            title.setText(getTitleStr());
        }

        inflater = LayoutInflater.from(this);
        View view = inflater.inflate(getLayoutId(), rootContainer, false);
        ButterKnife.bind(getSelfActivity(), view);

        if (unuseRefreshLayout()) {
            rootContainer.addView(view);
        } else {
            mRefreshLayout = new SmartRefreshLayout(mContext);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            params.weight = 1;
            mRefreshLayout.setLayoutParams(params);
            mRefreshLayout.setEnableRefresh(registerOnRefreshListener() != null);
            mRefreshLayout.setEnableLoadMore(registerOnLoadMoreListener() != null);
            mRefreshLayout.setOnRefreshListener(registerOnRefreshListener());
            mRefreshLayout.setOnLoadMoreListener(registerOnLoadMoreListener());
            mRefreshLayout.setEnableOverScrollDrag(true);
            mRefreshLayout.setDragRate(0.15f);
            mRefreshLayout.addView(view);
            rootContainer.addView(mRefreshLayout);
        }
    }

//    @Override
//    protected void attachBaseContext(Context newBase) {
//        final Resources res = newBase.getResources();
//        final Configuration config = res.getConfiguration();
//        config.fontScale=2f;//1 设置正常字体大小的倍数
//        super.attachBaseContext(newBase.createConfigurationContext(config));
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (registerEventBus() && mEventBus != null) {
            mEventBus.unregister(this);
        }
//        App.removeActivity(tag);
    }

    PopupWindow optionsPopupWindow;

    public void setOptions(OnOptionClickListener l, TextView... options) {
        if (options.length <= 0) {
            return;
        }
        if (optionsContainer.getChildCount() > 0) {
            optionsContainer.removeAllViews();
        }

        TextView tvOption = options[0];

        if (options.length > 1) {
            tvOption.append(" ▼");
            tvOption.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ScreenHelper.setBackgroundAlpha(getSelfActivity(), 0.5f);
                    if (optionsPopupWindow == null) {
                        LinearLayout linearLayout = new LinearLayout(mContext);
                        linearLayout.setPadding(10, 10, 10, 10);
                        linearLayout.setOrientation(LinearLayout.VERTICAL);
                        linearLayout.setBackgroundResource(com.bnyy.gbp.R.drawable.shape_bg_options);
                        for (int i = 1; i < options.length; i++) {
                            TextView option = options[i];
                            option.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    ScreenHelper.setBackgroundAlpha(getSelfActivity(), 1f);
                                    optionsPopupWindow.dismiss();
                                    l.onClick((TextView) v);
                                }
                            });
                            linearLayout.addView(option);
                            if (i != options.length - 1) {
                                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
                                View view = new View(mContext);
                                view.setLayoutParams(params);
                                view.setBackgroundColor(Color.parseColor("#eeeeee"));
                                linearLayout.addView(view);
                            }
                        }

                        optionsPopupWindow = new PopupWindow(ScreenUtils.getScreenWidth() / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
//                        optionsPopupWindow = new PopupWindow(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        optionsPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                ScreenHelper.setBackgroundAlpha(getSelfActivity(), 1f);
                            }
                        });
                        optionsPopupWindow.setOutsideTouchable(false);
                        optionsPopupWindow.setBackgroundDrawable(new ColorDrawable());
                        optionsPopupWindow.setFocusable(true);
                        optionsPopupWindow.setOutsideTouchable(true);
                        optionsPopupWindow.setContentView(linearLayout);
                    }
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager != null) {
                        inputMethodManager.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                    }
                    optionsPopupWindow.showAsDropDown(optionsContainer, 0, 0);
                }
            });
        } else {
            tvOption.setTextSize(14);
            tvOption.setTextColor(Color.parseColor("#333333"));
            tvOption.setEllipsize(TextUtils.TruncateAt.END);
            tvOption.setMaxLines(1);
            tvOption.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    l.onClick((TextView) v);
                }
            });
        }
        optionsContainer.addView(tvOption);
    }

    public void setOptions(TextView... options) {
        if (optionsContainer.getChildCount() > 0) {
            optionsContainer.removeAllViews();
        }
        optionsContainer.setVisibility(View.VISIBLE);
        if (options.length > 2) {
            // TODO: 2020/10/22  option数量大于1的时候改成弹窗列表的形式
        } else {
            for (TextView option : options) {
                option.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
                optionsContainer.addView(option);
            }
        }
    }

    public void setOptions(TextView option) {
        if (optionsContainer.getChildCount() > 0) {
            optionsContainer.removeAllViews();
        }
        optionsContainer.addView(option);
    }

    public interface OnOptionClickListener {
        void onClick(TextView option);
    }

    public void setOnBackClickListener(View.OnClickListener l) {
        back.setOnClickListener(l);
    }

    public void setTitleStr(String titleStr) {
        titleBar.setVisibility(View.VISIBLE);
        title = findViewById(com.bnyy.gbp.R.id.tv_title);
        title.setText(titleStr);
    }

    public void setStatusBarColor(int color) {
        StatusBarUtils.setStatusBarColor(this, color);
    }

    public interface LocationPermissionIsGrantListener {
        void isGrant(boolean grant);
    }
}
